package cn.com.cfae.iras.doc.analyze.components.rationality;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.FormatTimeUtil;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 内容合理性
 * M-4-1
 * 1、M-4章节，检查募集用途是否用于偿还有息债务；
 * 2、如果满足条件，检查有息债务表格中的每笔借款到期日期；表格table3
 * 3、差值早于到到期日≥60天；当天日期比还款到期日
 * 4、银行借款：涉及借款日期、到期日期；
 * 5、债券：涉及起息日、期限、到期日；
 * 5.1如果不存在到期日，通过公式计算，到期日=起息日+期限；
 * 6、如果不存在期限、到期日期提示缺失期限、到期日；
 * 7、逻辑判断错误，提示“借款即将到期
 *
 * 预评/发行阶段
 */
@Component("R1005")
@Scope("prototype")
public class R1005 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(R1005.class);
    @Autowired
    private HandingData handingData;
    @Autowired
    private FormatTimeUtil formatTimeUtil;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取R1005组件M");
        List<ComponentResult> componentResults = checkRulesR1005(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取R1005组件M");
        List<ComponentResult> componentResults = checkRulesR1005(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取R1005组件DM");
        List<ComponentResult> componentResults = checkRulesR1005(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取R1005组件BDM");
        List<ComponentResult> componentResults = checkRulesR1005(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    private List<ComponentResult> checkRulesR1005(String model,String catalogId,String chapterId,String ruleName){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;

        boolean flag = false;
        int startPage = 0;
        boolean isFlag = false;
        int jkrqPageNum = 0;
        List<ComponentResult.TextPosition> jkrqContentAndPositionList = null;

        int dqrqPageNum = 0;
        List<ComponentResult.TextPosition> dqrqContentAndPositionList = null;

        int jkqxPageNum = 0;
        List<ComponentResult.TextPosition> jkqxContentAndPositionList = null;

        int jkqzrPageNum = 0;
        List<ComponentResult.TextPosition> jkqzrContentAndPositionList = null;

        List<ComponentResult.TextPosition> chyxzwContentAndPositionList = null;
        int chyxzwPageNum = 0;
        boolean isAllSeem = false;
        boolean isAllErr = false;
        boolean isNotExist = false;
        String formatTime = "yyyyMMdd";
        boolean isContinue = false;
        try {
            if (extractData!=null){
                ChapterModel chapterModel =  extractData.getChapterModel(model);
                startPage = chapterModel!=null?chapterModel.getStartPage():0;
                //偿还有息债务
                MJZJYTType mjzjytType =null;
                if (chapterModel!=null){
                    extractItem = chapterModel.getModel("MJZJYT").getExtractItem("MJZJYT");
                    if (extractItem!=null){
                        KVText key = extractItem.getKey();
                        String text = key != null ? key.getText():null;
                        if (StringUtils.isNotEmpty(text)&&"YXZW".equals(text)||"YHJK".equals(text)){
                           // KVText yxzwValue = null;
                            List<TextLayout> textLayouts = null;
                            mjzjytType = MJZJYTType.valueOf(text);
                            switch (mjzjytType){
                                case YXZW:
                                    /*yxzwValue = extractItem.getValue();
                                    chyxzwPageNum = yxzwValue!=null?yxzwValue.getPageNumber():startPage;
                                    chyxzwContentAndPositionList = yxzwValue!=null?getContentAndPositionList(yxzwValue):null;*/
                                    textLayouts = key != null ? key.getTextLayoutList():null;
                                    chyxzwPageNum = CollectionUtils.isNotEmpty(textLayouts)?textLayouts.get(0).getPageNumber():startPage;
                                    chyxzwPageNum = chyxzwPageNum!=0?chyxzwPageNum:startPage;
                                    chyxzwContentAndPositionList = key!=null?getContentAndPositionList(key):null;
                                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"募集资金用途检查-偿还有息债务","已抽取",false,getRegulationId(),chyxzwPageNum,chyxzwContentAndPositionList,"01");
                                    componentResults.add(componentResult);
                                    isFlag = true;
                                    break;
                                case YHJK:
                                    /*yxzwValue = extractItem.getValue();
                                    chyxzwPageNum = yxzwValue!=null?yxzwValue.getPageNumber():startPage;
                                    chyxzwContentAndPositionList = yxzwValue!=null?getContentAndPositionList(yxzwValue):null;*/
                                    textLayouts = key != null ? key.getTextLayoutList():null;
                                    chyxzwPageNum = CollectionUtils.isNotEmpty(textLayouts)?textLayouts.get(0).getPageNumber():startPage;
                                    chyxzwPageNum = chyxzwPageNum!=0?chyxzwPageNum:startPage;
                                    chyxzwContentAndPositionList = key!=null?getContentAndPositionList(key):null;
                                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"募集资金用途检查-偿还有息债务","合理",false,getRegulationId(),chyxzwPageNum,chyxzwContentAndPositionList,"01");
                                    componentResults.add(componentResult);
                                    isFlag = true;
                                    break;
                            }
                        }
                    }

                    if (isFlag){

                        List<Map<String, ExtractItem>> yxzws = chapterModel.getModel("YXZW").getTables3();

                        if (CollectionUtils.isNotEmpty(yxzws)){
                            boolean isDQRFlag = false;
                            boolean isJKQXFlag = false;
                            boolean isJKRQFlag = false;
                            boolean isJKQZRFlag = false;
                            for (Map<String, ExtractItem> yxzw : yxzws){
                                 if (yxzw.isEmpty()){
                                    isAllSeem = true;
                                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查","基础数据未识别,请人工核对",true,getRegulationId(),chyxzwPageNum,chyxzwContentAndPositionList,"03");
                                    componentResults.add(componentResult);
                                    break;
                                }
                                Iterator<Map.Entry<String, ExtractItem>> entries = yxzw.entrySet().iterator();

                                while (entries.hasNext()){
                                    Map.Entry<String, ExtractItem> entry = entries.next();
                                    String type = entry!=null?entry.getKey():"";
                                    switch (type){
                                        //借款日期
                                        case YXZWModel.JKRQ:
                                            isJKRQFlag = true;
                                            break;
                                        //到期日期
                                        case YXZWModel.DQRQ:
                                            isDQRFlag = true;
                                            break;
                                        //借款期限
                                        case YXZWModel.JKQX:
                                            isJKQXFlag = true;
                                            break;
                                        //借款起止日
                                        case YXZWModel.JKQZR:
                                            isJKQZRFlag = true;
                                            break;
                                    }
                                }


                                if (isJKQZRFlag){
                                    isContinue = true;
                                }else if (isDQRFlag){
                                    isContinue = true;
                                }else if (isJKRQFlag&&isJKQXFlag){
                                    isContinue = true;
                                }else{
                                    isAllSeem = true;
                                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日期检查","到期日期缺失,建议人工核对",true,getRegulationId(),startPage,dqrqContentAndPositionList,"03");
                                    componentResults.add(componentResult);
                                    if (!isJKQXFlag){
                                        isAllSeem = true;
                                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款期限检查","借款期限缺失,建议人工核对",true,getRegulationId(),startPage,jkqxContentAndPositionList,"03");
                                        componentResults.add(componentResult);
                                    }
                                }

                                break;
                            }

                        }else {
                            isAllSeem = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查","基础数据未识别,请人工核对",true,getRegulationId(),startPage,jkqxContentAndPositionList,"03");
                            componentResults.add(componentResult);
                        }


                        if (isContinue){


                            String regex = "(\\d+(.)?)?\\d+";
                            SimpleDateFormat df = new SimpleDateFormat(formatTime);
                            String day = df.format(new Date());

                            Pattern pattern = Pattern.compile(regex);
                            for (Map<String, ExtractItem> yxzw : yxzws){
                                String jkrq = null;
                                String dqrq = null;
                                String jkqx = null;
                                String jkqxText = null;
                                String jkqzr = null;
                                Iterator<Map.Entry<String, ExtractItem>> entries = yxzw.entrySet().iterator();

                                while (entries.hasNext()){
                                    Map.Entry<String, ExtractItem> entry = entries.next();
                                    ExtractItem jkyeValue = entry!=null?entry.getValue():null;
                                    KVText value = null;
                                    if (jkyeValue!=null){
                                        value = jkyeValue.getValue();
                                    }
                                    String type = entry!=null?entry.getKey():"";
                                    switch (type){
                                        //借款日期
                                        case YXZWModel.JKRQ:
                                            jkrqPageNum = value!=null?value.getPageNumber():0;
                                            jkrqPageNum = jkrqPageNum!=0?jkrqPageNum:startPage;
                                            jkrqContentAndPositionList = value!=null?getContentAndPositionList(value):null;
                                            jkrq = value!=null?value.getText():null;

                                            break;
                                        //到期日期
                                        case YXZWModel.DQRQ:
                                            dqrqPageNum = value!=null?value.getPageNumber():0;
                                            dqrqPageNum = dqrqPageNum!=0?dqrqPageNum:startPage;
                                            dqrqContentAndPositionList = value!=null?getContentAndPositionList(value):null;
                                            dqrq = value!=null?value.getText():null;
                                            break;
                                        //借款期限
                                        case YXZWModel.JKQX:
                                            jkqxPageNum = value!=null?value.getPageNumber():0;
                                            jkqxPageNum = jkqxPageNum!=0?jkqxPageNum:startPage;
                                            jkqxContentAndPositionList = value!=null?getContentAndPositionList(value):null;
                                            jkqxText = value!=null?value.getText():null;
                                            jkqx = jkqxText;
                                            if (StringUtils.isNotEmpty(jkqx)){
                                                Matcher matcher = pattern.matcher(jkqx);
                                                StringBuffer str = new StringBuffer();
                                                while (matcher.find()){
                                                    str.append(matcher.group());
                                                }
                                                jkqx = str.toString();
                                            }
                                            break;
                                        //借款起止日
                                        case YXZWModel.JKQZR:
                                            jkqzrPageNum = value!=null?value.getPageNumber():0;
                                            jkqxPageNum = jkqzrPageNum!=0?jkqzrPageNum:startPage;
                                            jkqzrContentAndPositionList = value!=null?getContentAndPositionList(value):null;
                                            jkqzr = value!=null?value.getText():null;
                                            break;
                                    }
                                }

                                if (StringUtils.isNotEmpty(jkqzr)){
                                    String jkqz = null;
                                    Matcher matcher = pattern.matcher(jkqzr);
                                    List<String> date = new ArrayList<>();
                                    while (matcher.find()){
                                        date.add(matcher.group());
                                    }
                                    if (CollectionUtils.isNotEmpty(date)&&date.size()==6){
                                        for (int i=0;i<date.size();i++){
                                            String t = date.get(i);
                                            if (t.length()<2){
                                                date.set(i,"0"+t);
                                            }
                                        }
                                        jkqz = date.get(3)+date.get(4)+date.get(5);
                                    }
                                    if (StringUtils.isNotEmpty(jkqz)&&jkqz.length()==8){
                                        long dVale = formatTimeUtil.getTimeDValue(day,jkqz,formatTime);
                                        if (dVale>=60){
                                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"借款起止日日期为:"+jkqzr,"合理",false,getRegulationId(),jkqzrPageNum,jkqzrContentAndPositionList,"01");
                                            componentResults.add(componentResult);
                                        }else if (dVale<60&&dVale>0){
                                            isAllErr = true;
                                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"借款起止日日期为:"+jkqzr,"借款即将到期",true,getRegulationId(),jkqzrPageNum,jkqzrContentAndPositionList,"02");
                                            componentResults.add(componentResult);
                                        }else {
                                            isAllErr = true;
                                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"借款起止日日期为:"+jkqzr,"借款已到期",true,getRegulationId(),jkqzrPageNum,jkqzrContentAndPositionList,"02");
                                            componentResults.add(componentResult);
                                        }
                                    }
                                }else {
                                    if (StringUtils.isNotEmpty(dqrq)){
                                        String dqrqStr = formatTimeUtil.formatTime(dqrq);
                                        if (StringUtils.isNotEmpty(dqrqStr)&&dqrqStr.length()==8){
                                            long dVale = formatTimeUtil.getTimeDValue(day,dqrqStr,formatTime);
                                            if (dVale>=60){
                                                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"到期日期为:"+dqrq,"合理",false,getRegulationId(),dqrqPageNum,dqrqContentAndPositionList,"01");
                                                componentResults.add(componentResult);
                                            }else if (dVale<60&&dVale>0){
                                                isAllErr = true;
                                                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"到期日期为:"+dqrq,"借款即将到期",true,getRegulationId(),dqrqPageNum,dqrqContentAndPositionList,"02");
                                                componentResults.add(componentResult);
                                            }else {
                                                isAllErr = true;
                                                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"到期日期为:"+dqrq,"借款已到期",true,getRegulationId(),dqrqPageNum,dqrqContentAndPositionList,"02");
                                                componentResults.add(componentResult);
                                            }
                                        }

                                    }else {
                                        if (StringUtils.isNotEmpty(jkrq)&&StringUtils.isNotEmpty(jkqx)){
                                            String jkrqStr = formatTimeUtil.formatTime(jkrq);
                                            if (StringUtils.isNotEmpty(jkrqStr)&&jkrqStr.length()==8){
                                                String type = null;
                                                int jkqxt = 0;
                                                if (jkqxText.contains("年")){
                                                    if (jkqx.contains(".")){
                                                        BigDecimal jkqxdBigDecimal = new BigDecimal(jkqx);
                                                        BigDecimal divide = new BigDecimal("365").multiply(jkqxdBigDecimal).setScale(0,BigDecimal.ROUND_HALF_UP);;
                                                        jkqxt = divide.intValue();
                                                        type = "DAY";
                                                    }else {
                                                        jkqxt = Integer.parseInt(jkqx);
                                                        type = "YEAR";

                                                    }
                                                }else if (jkqxText.contains("天")){
                                                    jkqxt = Integer.parseInt(jkqx);
                                                    type = "DAY";
                                                }else {
                                                    jkqxt = Integer.parseInt(jkqx);
                                                    type = "DAY";
                                                }

                                                String dqr = formatTimeUtil.getTimeOfSet(jkrqStr,type,jkqxt,formatTime);
                                                long dVale = formatTimeUtil.getTimeDValue(day,dqr,formatTime);
                                                if (dVale>=60){
                                                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"借款日期为:"+jkrq+",借款期限为:"+jkqxText,"合理",false,getRegulationId(),jkrqPageNum,jkrqContentAndPositionList,"01");
                                                    componentResults.add(componentResult);
                                                }else if (dVale<60&&dVale>0){
                                                    isAllErr = true;
                                                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"借款日期为:"+jkrq+",借款期限为:"+jkqxText,"借款即将到期",true,getRegulationId(),jkrqPageNum,jkrqContentAndPositionList,"02");
                                                    componentResults.add(componentResult);
                                                }else {
                                                    isAllErr = true;
                                                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查-"+"借款日期为:"+jkrq+",借款期限为:"+jkqxText,"借款已到期",true,getRegulationId(),jkrqPageNum,jkrqContentAndPositionList,"02");
                                                    componentResults.add(componentResult);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }


            if (isFlag){

                if (isAllErr){
                    for (ComponentResult result:componentResults){
                        result.setExist("02");
                    }
                }
                if (isAllSeem){
                    for (ComponentResult result:componentResults){
                        result.setExist("03");
                    }
                }
            }else {
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"募集资金用途检查-偿还有息债务","未识别,建议人工核对",true,getRegulationId(),startPage,null,"03");
                componentResults.add(componentResult);
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查","未触发检查",true,getRegulationId(),startPage,null,"03");
                componentResults.add(componentResult);
            }

        }catch (Exception e){
            componentResults.clear();
            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"募集资金用途检查-偿还有息债务","未识别,建议人工核对",true,getRegulationId(),startPage,null,"03");
            componentResults.add(componentResult);
            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"贷款到期日检查","未触发检查",true,getRegulationId(),startPage,null,"03");
            componentResults.add(componentResult);
            log.error(e.getMessage(),e);
        }
        return  componentResults;
    }
}
